package com.lansetech.framework.redis.peak.shaving;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import redis.clients.jedis.Jedis;
import redis.clients.util.SafeEncoder;

public class PeakShavingService {
    private final MessageStringifier messageStringifier;

    private final PeakShavingRunnableContext context;

    private final RedisConnectionFactory connectionFactory;

    public PeakShavingService(MessageStringifier messageStringifier, PeakShavingRunnableContext context) {
        this.messageStringifier = messageStringifier;
        this.context = context;
        this.connectionFactory = this.context.getConnectionFactory();
    }

    public PeakShavingService(MessageStringifier messageStringifier, PeakShavingListener listener){
        this(messageStringifier, listener.getContext());
    }

    public void saveToRedis(Object object){
        int key = messageStringifier.key(object);
        String type = messageStringifier.type(object);
        if(type == null){
            throw new RuntimeException("未知的请求类型");
        }
        String value = messageStringifier.stringify(object);
        String queueName = context.getConfig().fallInQueueName(type, key);
        RedisConnection connection = null;
        try{
            connection = connectionFactory.getConnection();
            connection.lPush(SafeEncoder.encode(queueName), SafeEncoder.encode(value));
        }finally {
            if(connection != null){
                connection.close();
            }
        }
    }
}
